package cn.fzm.ssm.service.impl;

import cn.fzm.ssm.dao.IUserDao;
import cn.fzm.ssm.domain.Role;
import cn.fzm.ssm.domain.UserInfo;
import cn.fzm.ssm.service.IUserService;
import cn.fzm.ssm.utils.BCryptPasswordEncoderUtils;
import cn.fzm.ssm.utils.UUIDUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Dremeue
 * @create 2019-10-12 12:52
 **/
@Service("userService")
@Transactional
public class UserService implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsername(username);
        User user = new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus() == 0 ? false :
                true, true, true, true, getAuthorities(userInfo.getRoles()));
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthorities(List<Role> roles) {

        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();

        // 将roles中的角色名拼到权限中
        for (Role role : roles) {
            authorityList.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }

        return authorityList;
    }

    @Override
    public UserInfo findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public List<UserInfo> findAll(int pageNum, int PageSize) {
        PageHelper.startPage(pageNum, PageSize);
        return userDao.findAll();
    }

    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(UUIDUtils.getUUID());
        userInfo.setPassword(BCryptPasswordEncoderUtils.encodePassword(userInfo.getPassword()));
        userDao.save(userInfo);
    }

    @Override
    public void deleteByIds(String[] ids) {
        userDao.deleteByIds(ids);
    }

    @Override
    public void addRoleToUser(String userId, String[] ids) {
        for (String roleId : ids) {
            userDao.addRoleToUser(userId, roleId);
        }
    }
}
